<template>
  <a-modal
    :title='title'
    :width='720'
    :visible='visible'
    :confirmLoading='confirmLoading'
    :maskClosable='false'
    :destroyOnClose='true'
    @cancel='handleCancel'
  >
    <div class='table-operator'>
      <!-- 操作板块 -->
      <a-button
        type='primary'
        @click='handleMakeQrcode'
      >创建二维码
      </a-button>
      <a-button
        type='primary'
        @click='handleCreate(1)'
      >创建文本
      </a-button>
    </div>
    <a-spin :spinning='confirmLoading'>
      <s-table
        ref='table'
        rowKey='id'
        :showPagination='false'
        :columns='columns'
        :data='loadData'
      >
          <span slot='type' slot-scope='text'>
          {{ WorkTypeEnum.getNameByValue(text) }}
      </span>
        <span slot='status' slot-scope='text'>
          <a-tag :color='WorkStatusEnum.valueOf(text).color'>{{ WorkStatusEnum.getNameByValue(text) }}</a-tag>
      </span>
        <span class='actions' slot='action' slot-scope='text,item'>
          <a v-action:download
             v-if='item.status === WorkStatusEnum.COMPLETED.value'
             @click='handleDownload(item.id)'
          >下载</a>
      </span>
      </s-table>
    </a-spin>
    <a-modal
      title='创建二维码'
      :width='720'
      :visible='visibleQrcode'
      :confirmLoading='confirmLoading'
      :maskClosable='false'
      :destroyOnClose='true'
      @cancel='handleCancelQrcode'
      @ok='handleSubmitQrcode'
    >
      <a-row>
        <a-col :span='12'>
          <a-form :model="formData" :label-col="labelCol" :wrapper-col="wrapperCol">
            <a-form-item label="二维码大小">
              <a-select v-model:value="formData.size"  loading :options="sizeList" ></a-select>
            </a-form-item>
            <a-form-item label="边框">
              <a-slider  v-model:value="formData.margin" :min='1' :max='10' @change='makeQrcode' />

            </a-form-item>
            <a-form-item label="背景色">
              <colorPicker ref='colorPicker' v-model='formData.backgroundColor' @change='makeQrcode'/>
            </a-form-item>
            <a-form-item label="码色">
              <colorPicker ref='colorPicker' v-model='formData.foregroundColor' @change='makeQrcode'/>
            </a-form-item>
            <a-form-item label="logo大小">
              <a-slider  v-model:value="formData.logoResize" :min='50' :max='300'  />
            </a-form-item>
            <a-form-item label="logo">
              <div class='img' @click.stop='handleSelectImage'>
                <div v-if='imageUrl' class='img-cover' :style="{ backgroundImage: `url('${imageUrl}')` }"></div>
                <a-icon v-else type='plus'></a-icon>
              </div>
            </a-form-item>
          </a-form>
        </a-col>
        <a-col :span='12'>
          <div class='qr-box'>
          <canvas id='qrCanvas' style='border: 1px solid #ccc;'/>
          <img v-if='imageUrl' :src='imageUrl' :width='logoWH' :height='logoWH'>
          </div>
        </a-col>
      </a-row>
    </a-modal>
    <FilesModal
      ref='FilesModal'
      @handleSubmit='handleSelectImageSubmit'
    />
  </a-modal>
</template>

<script>
import * as Api from '@/api/book/work'
import WorkStatusEnum from '@/common/enum/workStatus'
import { STable } from '@/components'
import ItemForm from '@/views/book/modules/ItemForm'
import WorkTypeEnum from '@/common/enum/workType'
import qrcode from 'qrcode'
import vcolorpicker from 'vcolorpicker'
import Vue from 'vue'
import FilesModal from '@/components/Modal/FilesModal/FilesModal'
import cloneDeep from 'lodash.clonedeep'
Vue.use(vcolorpicker)
export default {
  name: 'makeCode',
  components: {
    STable, ItemForm,FilesModal

  },
  computed:{
    logoWH(){return this.formData.logoResize >300?300:this.formData.logoResize}
  },
  data() {
    return {
      WorkStatusEnum,
      WorkTypeEnum,
      // 对话框标题
      title: '',
      content:'http://book.whbjswh.com/#/pages/book/detail?id=G77blq2341j23l4kjdLFzlcxkv',
      color:'',
      // 标签布局属性
      labelCol: { span: 7 },
      // 输入框布局属性
      wrapperCol: {
        span: 13
      },
      visibleQrcode:false,
      type: '',
      typeText: '',
      refId: '',
      // modal(对话框)是否可见
      visible: false,
      // modal(对话框)确定按钮 loading
      confirmLoading: false,
      // 当前表单元素
      // form: this.$form.createForm(this),
      // 当前记录
      formData:{
        size:300,
        margin:1,
        logoId:'',
        logoResize:100,
        foregroundColor:'#000000',
        backgroundColor:'#ffffff',
      },
      logoResize:100,
      imageUrl:'',
      sizeList:[
        {value:300,label:300},
        {value:500,label:500},
        {value:800,label:800}
      ],
      columns: [
        {
          title: 'ID',
          dataIndex: 'id'
        },
        {
          title: '类型',
          dataIndex: 'type',
          scopedSlots: { customRender: 'type' }
        },
        {
          title: '数量',
          dataIndex: 'file_num'
        },
        {
          title: '创建时间',
          dataIndex: 'create_time'
        },
        {
          title: '状态',
          dataIndex: 'status',
          scopedSlots: { customRender: 'status' }
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: '180px',
          scopedSlots: { customRender: 'action' }
        }
      ],
      loadData: params => {
        return Api.list({
          type: [this.type, this.typeText],
          refId: this.refId
        }).then(res => {
          return { data: res.data, pagination: {} }
        })
      }
    }
  },
  methods: {
    open(type, typeText, refId) {
      this.visible = true
      this.type = type
      this.typeText = typeText
      this.refId = refId

    },
    handleMakeQrcode(){
      this.formData={
        size:300,
        margin:1,
        logoId:'',
        logoResize:100,
        foregroundColor:'#000000',
        backgroundColor:'#ffffff',
      }
      this.imageUrl=''
      this.visibleQrcode=true
      setTimeout(()=> {
        this.makeQrcode()
      },150)
    },
    makeQrcode(){
      qrcode.toCanvas(document.getElementById('qrCanvas'),this.content,{
        width:300,
        margin:this.formData.margin,
        color:{
          dark:this.formData.foregroundColor,
          light:this.formData.backgroundColor,
        }
      })
    },
    handleCreate(type,config) {
      this.confirmLoading = true

      Api.create({
        type: type === 0 ? this.type : this.typeText,
        ref_id: this.refId,
        config,
      }).then(res => {
        this.$refs.table.refresh()
        this.$message.success('创建成功，正在打包。。。请稍后下载')
      }).finally(() => {
        this.confirmLoading = false
      })
    },
    handleCancel() {
      this.visible = false
    },
    download(url) {
      const a = document.createElement('a')
      a.href = this.$store.getters['domain'] + url
      a.target = '_blank'
      a.click()
      a.remove()
    },
    handleDownload(id) {
      Api.download({ id }).then(res => {
        this.download(res.data.url)
      })
    },
    handleCancelQrcode(){
      this.visibleQrcode=false
    },
    hexToRgb(hex) {
      let r = parseInt(hex.substring(1, 3), 16);
      let g = parseInt(hex.substring(3, 5), 16);
      let b = parseInt(hex.substring(5, 7), 16);
      return [ r, g, b ];
    },
    handleSelectImage() {
      this.$refs.FilesModal.show()
    },
    handleSelectImageSubmit(result){
      this.imageUrl=result[0].preview_url
      this.formData.logoId = result[0].file_id
    },
    handleSubmitQrcode(){
      const config = cloneDeep( this.formData)
      config.foregroundColor=config.foregroundColor ==='#000000'?'':this.hexToRgb(config.foregroundColor)
      config.backgroundColor=config.backgroundColor ==='#ffffff'?'':this.hexToRgb(config.backgroundColor)
      config.margin = config.margin*10
      if(config.logoId){
        config.logoResize = Math.round(config.size/300 * config.logoResize)
      }
      this.handleCancelQrcode()
      this.handleCreate(0,config)
    },
  }
}
</script>

<style scoped>
.table-operator button {
  margin-right: 10px;
}
>>> .m-colorPicker{
  cursor: pointer;
  padding: 5px;
  border:1px solid #ccc;
}
>>> .m-colorPicker .colorBtn{
  width: 20px;
  height: 20px;
}

.img-cover {
  display: block;
  width: 100%;
  height: 100%;
  background: no-repeat center center / 100%;
}
.img {
  width: 80px;
  height: 80px;
  padding: 2px;
  border: 1px dashed #e2e2e2;
  background: #fff;
  text-align: center;
  display: flex;
  justify-content: center;
  align-items: center;
}
.img i {
  font-size: 32px;
}
.qr-box{
  position: relative;
  width: 302px;
  height: 302px;
  display: flex;
  align-items: center;
  justify-content: center;
}
.qr-box #qrCanvas{
  position: absolute;
  top:0;
  left: 0;
  z-index: 0;
}
.qr-box img{
  z-index: 1;
  transition-duration:.15s;
}



</style>